package net.zjitc.security;

import cn.hutool.json.JSONUtil;
import net.zjitc.common.ResponseResult;
import net.zjitc.entity.Manager;
import net.zjitc.service.ManagerService;
import net.zjitc.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 毛钰深
 * @create 2022/1/23
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private ManagerService managerService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //设置响应头
        httpServletResponse.setContentType("application/json;charset-UTF-8");
        //获取response的输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        ResponseResult<Manager> res;
        //成功就生成jwt,并放置到response的header中
        String jwt = jwtUtils.generateToken(authentication.getName());
        //响应头设置
        httpServletResponse.setHeader(jwtUtils.getHeader(),jwt);

        //查询用户相关的信息,并且封装到实体类中
        res=managerService.selectByUsername(authentication.getName());
        res.getData().setToken(jwt);

        //使用工具类将res的数据写到输出流中并返回
        outputStream.write(JSONUtil.toJsonStr(res).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();

    }
}
